package com.example.controller;

import cn.hutool.json.JSONString;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.core.lang.TypeReference;
import com.example.config.ShopBean;
import com.example.config.UploadBean;
import com.example.entity.ShopList;
import com.example.result.CommonResult;
import com.example.service.ShopListService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: tobed
 * @date: 2022/11/20
 * @time: 20:51
 */
@RestController
@RequestMapping("shopList")
public class ShopListController {

    @Autowired
    ShopListService service;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Resource
    Redisson redisson;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("list")
    public CommonResult list() {
        if (stringRedisTemplate.opsForValue().get("ShopList") != null) {
            List<ShopList> shopLists = JSONUtil.toBean(stringRedisTemplate.opsForValue().get("ShopList"), new TypeReference<List<ShopList>>() {
            }, true);
            return CommonResult.ok(shopLists);
        } else {
            List<ShopList> list = service.list();
            stringRedisTemplate.opsForValue().set("ShopList",JSONObject.toJSONString(list));
            return CommonResult.ok(list);
        }
    }

//    @RequestMapping("deduct_stock/{id}")
//    public CommonResult deductStock(@PathParam("id")Integer id) throws InterruptedException {
//        String lockKey = "lock_key";
//        // 获取锁对象
//        RLock redissonLock = redisson.getLock(lockKey);
//        try{
//            //加锁
//            redissonLock.lock();
//            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("shop_stock"));
//            if (stock>0){
//                int realStock = stock -1;
//                stringRedisTemplate.opsForValue().set("shop_stock",realStock + "");
//                System.out.println("库存扣减成功 剩余库存"+realStock);
//                return CommonResult.ok();
//            }else{
//                System.out.println("库存扣除失败 ，库存不足");
//                return CommonResult.fail(888,"库存扣除失败 ，库存不足");
//            }
//        }finally {
//            Thread.sleep(200);
//            // 解锁
//            redissonLock.unlock();
//        }
//    }


//    @RequestMapping("deduct_stock/{id}")
//    public void deductStock(@PathParam("id") Integer id) throws InterruptedException {
//        String lockKey = "lock_key";
//        // 获取锁对象
//        RLock redissonLock = redisson.getLock(lockKey);
//        try {
//            //加锁
//            redissonLock.lock();
//            List<ShopList> shopLists = JSONUtil.toBean(stringRedisTemplate.opsForValue().get("ShopList"), new TypeReference<List<ShopList>>() {
//            }, true);
//            int restuCode = 0;
//            for (int i = 0; i < shopLists.size(); i++) {
//                if (id == shopLists.get(i).getId() && shopLists.get(i).getShopTotal() > 0) {
//                    int realStock = shopLists.get(i).getShopTotal() - 1;
//                    shopLists.get(i).setShopTotal(realStock);
//                    stringRedisTemplate.opsForValue().set("ShopList", JSONObject.toJSONString(shopLists));
//                    restuCode = 1;
//                } else {
//                    System.out.println("库存扣除失败 ，库存不足");
//                    restuCode = 0;
//                    return CommonResult.fail(888, "库存扣除失败 ，库存不足");
//                }
//            }
//        } finally {
//            // 解锁
//            redissonLock.unlock();
//        }
//    }

    @RequestMapping("deduct_stock/{id}/{userId}")
    public CommonResult deductStock(@PathVariable Integer id,@PathVariable Integer userId) throws InterruptedException {
        int result = 0;
        String lockKey = "lock_key";
        // 获取锁对象
        RLock redissonLock = redisson.getLock(lockKey);
        try {
            //加锁
            redissonLock.lock();
            List<ShopList> shopLists = JSONUtil.toBean(stringRedisTemplate.opsForValue().get("ShopList"), new TypeReference<List<ShopList>>() {
            }, true);
            for (int i = 0; i < shopLists.size(); i++) {
                if (id == shopLists.get(i).getId() && shopLists.get(i).getShopTotal() > 0) {
                    int realStock = shopLists.get(i).getShopTotal() - 1;
                    shopLists.get(i).setShopTotal(realStock);
                    stringRedisTemplate.opsForValue().set("ShopList", JSONObject.toJSONString(shopLists));
                    Message message = MessageBuilder.withBody(String.valueOf(id).getBytes()).setMessageId(String.valueOf(userId)).build();
                    rabbitTemplate.convertAndSend(UploadBean.CREATE_SHOP_QUEUE_NAME,message);
                    result = 1;
                } else {
                    System.out.println("库存扣除失败 ，库存不足");
                }
            }
        } finally {
            // 解锁
            redissonLock.unlock();
        }
        if (result == 1){
            return CommonResult.ok();
        }else{
            return CommonResult.fail(888, "库存扣除失败 ，库存不足");
        }
    }


}
